package com.fanhao.dllo.soundfm.service;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.SeekBar;

import com.fanhao.dllo.soundfm.entity.ServiceToUiString;
import com.fanhao.dllo.soundfm.entity.UiToServiceString;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;


/**
 * Created by dllo on 16/1/22.
 */
public class MusicService extends Service implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnPreparedListener {
    private MediaPlayer player;
    private SeekBar seekBar;


    // 获得PlayActivity的SeekBar,来对它进行设置
    public void setSeekBar(SeekBar seekBar) {
        this.seekBar = seekBar;
        // seekBar的拖动监听事件
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int pro;

            // 当前进度
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                Log.d("AAA", "------->" + progress);
                // 如果被拖动
                if (fromUser) {
                    // 设置播放器的位置为 seekBar拖动后的位置
                    player.seekTo(progress);
                }
            }

            // 开始拖动
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Log.d("AAA", "------->" + "开始拖动");
            }

            // 拖动停止
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                handler.sendEmptyMessage(0);
                Log.d("AAA", "------->" + "结束拖动");
            }
        });
    }


    // 计时器
    private Timer timer = new Timer();

    // 计时器 timer需要的一个参数
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            if (player != null) {
                if (player.isPlaying() && seekBar.isPressed() == false) {
                    // 给handler发送消息,使其不断刷新
                    handler.sendEmptyMessage(0);
                }
            }
        }

    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (player.getDuration() >= 0) {
                //player当前音乐的总时长
                seekBar.setMax(player.getDuration());
                //player当前的播放位置
                seekBar.setProgress(player.getCurrentPosition());
            }
        }
    };


    @Override
    public void onCreate() {
        super.onCreate();
        try {
            player = new MediaPlayer();
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型
            player.setOnBufferingUpdateListener(this);
            player.setOnPreparedListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 通过计时器来进行每一秒的刷新
        timer.schedule(timerTask, 0, 1000);

        // 注册阅读
        EventBus.getDefault().register(this);
    }

    // 接收从MainActivity传来的信息,然后停止音乐
    public void onEvent(String stop) {
        MediaPause();
    }

    // 接收从MainActivity传来的信息,然后继续播放音乐
    public void onEvent(Integer i) {
        MediaRestart();
    }

    // 接收Mainactivity传来的seekBar,并赋给MusicService
    // 通过这种方法来设置点击后进入PlayActivity的seekBar
    public void onEvent(SeekBar seekBar){
        setSeekBar(seekBar);
    }

    // 接收从UI线程发送过来的类UiToServiceString,
    // 通过判断type的值得不同,进行相应的操作
    public void onEvent(UiToServiceString uiToServiceString){

        if (uiToServiceString.getType() == 1){
            // 播放音乐
            MediaPlay(uiToServiceString.getContent());
            Log.d("MusicService", "progress:--------->");
        }
        else if (uiToServiceString.getType() == 2){
            // from PlayActivity
            // 暂停音乐
            MediaPause();
        }
        else if (uiToServiceString.getType() == 3){
            // from PlayActivity
            // 继续播放音乐
            MediaRestart();
        }
        else if (uiToServiceString.getType() == 4){
            // 从MainActivity点击relativeLeft后发送过来的
            int progress = seekBar.getProgress();
            int max = seekBar.getMax();
            // 发送回Mainactivity
            EventBus.getDefault().post(new ServiceToUiString(1,progress, max));
        }
        else if (uiToServiceString.getType() == 5){
            // from PlayActivity
            // 为了不断刷新
            // Mainactivity点击后进入的PlayActivityseek
            // 里的SeekBar
            // 有点绕哈
//            seekBar.setMax(player.getDuration());
//            seekBar.setProgress(player.getCurrentPosition());

        }
    }

    // startService启动时,会实现的方法
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    // 绑定服务的方法
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new Con();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        if (player != null){
            if (player.isPlaying()){
                player.stop();
            }
            player.release();
            player = null;
        }
        return super.onUnbind(intent);
    }

    // 继承Binder,返回MusicService对象
    public class Con extends Binder {

        public MusicService getService() {
            return MusicService.this;
        }
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        seekBar.setSecondaryProgress(percent);
    }

    // 音乐的播放方法
    public void MediaPlay(String url) {
        try {
            player.reset();
            player.setDataSource(url);// 设置数据源
            player.prepare(); // prepare自动播放
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 音乐的暂停方法
    public void MediaPause() {
        player.pause();
    }

    // 音乐的继续播放方法
    public void MediaRestart() {
        player.start();
    }

    // 音乐的结束方法
    public void MediaStop() {
        player.stop();
        // 释放对象
        player.release();
    }

    @Override
    public void onPrepared(MediaPlayer mp) {

        mp.start();
    }


}
